#include "ui_bofugui.h"
#include "bofugui.h"


/********************************************************************************************/
//3

void BofuGui::on_wav2rawButton_clicked()
{
    ui->statusBar->showMessage(tr("Converting wav files...please wait!!!"),5000);

    logDate();
    command = "cd "+dir.absolutePath()+"; perl "+bofu.absolutePath()+"/convert/convert.pl -sdir wav/ -list filelist.txt -conv w2r >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"wav-files converted. If the raw folder is empty you probably have not installed 'sox'!\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}


void BofuGui::on_raw2wavButton_clicked()
{
    ui->statusBar->showMessage(tr("Converting raw files...please wait!!!"),5000);

    logDate();
    command = "cd "+dir.absolutePath()+"; perl "+bofu.absolutePath()+"/convert/convert.pl -sdir raw -list filelist.txt -conv r2w >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"raw-files converted. If the wav folder is empty you probably have not installed 'sox'!\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

/********************************************************************************************/

//5.1
void BofuGui::on_lab2blfButton_clicked()
{
    if ((!transcriptionfile.exists())){
        errorFiles();
    }else {
        ui->statusBar->showMessage(tr("Creating blf files...please wait!!!"),5000);

        logDate();
        command = "cd "+dir.absolutePath()+"; perl "+bofu.absolutePath()+"/lab2blf/lab2blf.pl -lab lab/ -sent transcription.txt -list filelist.txt >> "+korpusname+".log 2>&1";
        commandexec = system(command.toAscii().data());
        writeToLog("echo \"blf-files created\" >> "+dir.absolutePath()+"/"+korpusname+".log");
        waitSecs(5);
        scriptDone();
    }
}

//5.2
void BofuGui::on_pushButton_browsePhoxysymbols_clicked()
{
    QString sourceFile= QFileDialog::getOpenFileName(this, tr("Loading phoxysymbols file"), QDir::homePath());
    if (!sourceFile.isEmpty()){
        phoxsysymbolsfile= sourceFile;

        ui->statusBar->showMessage(tr("Phoxsysymbols-File loaded"),5000);
        ui->checkBox_withPhoxsy->setEnabled(1);

    } else ui->checkBox_withPhoxsy->setEnabled(0);
}

void BofuGui::on_blf2xmlButton_clicked()
{

    ui->statusBar->showMessage(tr("Creating xml files...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; blf2xml -list filelist.txt -ldir blf/ -xdir xml/";
    if (ui->checkBox_withPhoxsy->isChecked()){
    command.append(" -phoxsysymbols "+ phoxsysymbolsfile);
    }
    command.append(" >> "+korpusname+".log 2>&1");
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"xml-files created\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    scriptDone();

}

//5.3
void BofuGui::on_addPhrasesButton_clicked()
{
    ui->statusBar->showMessage(tr("Adding phrasal information...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; addphrases -list filelist.txt -xdir xml/ >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"Phrasal information added\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

//5.4
void BofuGui::on_alignFlagButton_clicked()
{
    ui->statusBar->showMessage(tr("Selecting units...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; alignflag -manual -list filelist.txt -xdir xml/ >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"Units selected\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();

}

//5.5
void BofuGui::on_editContextButton_clicked()
{
    if ((!contextfile.exists())){
        logDate();
        copyFile(exe.absolutePath()+"/.data/example/context_classes.txt",dir.absolutePath()+"/context_classes.txt");
        writeToLog("echo \"contextfile created\" >> "+dir.absolutePath()+"/"+korpusname+".log");
        ui->statusBar->showMessage(tr("Contextfile created"),5000);
        scriptDone();
    }

    ui->statusBar->showMessage(tr("Opening contextfile"),5000);
    QUrl url( ""+dir.absolutePath()+"/context_classes.txt" );
    QDesktopServices::openUrl( url );

}
void BofuGui::on_addContextButton_clicked()
{
    ui->statusBar->showMessage(tr("Adding context...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; addcontext -list filelist.txt -xdir xml/ -ccfile context_classes.txt >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"Context added\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

//5.6
void BofuGui::on_addHPButton_clicked()
{
    ui->statusBar->showMessage(tr("Adding halfphones...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; addhp -list filelist.txt -xdir xml/ >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"Halfphones added\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

//5.7
void BofuGui::on_optBoundsButton_clicked()
{
    ui->statusBar->showMessage(tr("Optimizing bounds...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; optbounds -list filelist.txt -xdir xml/ -adir raw/ >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"Bounds optimized\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

//5.8
void BofuGui::on_addmelboundsButton_clicked()
{
    ui->statusBar->showMessage(tr("Adding MFCCs...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; melbounds -list filelist.txt -xdir xml/ -adir raw/ >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"MFCCs added\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

//5.9
void BofuGui::on_addF0Button_clicked()
{
    ui->statusBar->showMessage(tr("Adding F0 values...please wait!!!"),5000);
    logDate();
    command = "cd "+dir.absolutePath()+"; addf0 -list filelist.txt -xdir xml/ -fdir f0/ >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"f0 added\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

void BofuGui::on_getF0BossButton_clicked()
{
    ui->statusBar->showMessage(tr("Extracting F0 values...please wait!!!"),5000);
    command = "mkdir "+dir.absolutePath()+"/f0";
    QDir f0( (dir.absolutePath()+"/f0").toAscii().data() );
    if ( !f0.exists() ){
        commandexec = system(command.toAscii().data());
    } else{
        //qWarning( "Folder already exists" );
    }
    logDate();
    command = "cd "+dir.absolutePath()+"; sh "+bofu.absolutePath()+"/snackf0boss/snackf0boss.sh >> "+korpusname+".log 2>&1";
    commandexec = system(command.toAscii().data());
    writeToLog("echo \"f0 extracted\" >> "+dir.absolutePath()+"/"+korpusname+".log");
    waitSecs(5);
    scriptDone();
}

/********************************************************************************************/

//5.10.2
void BofuGui::on_pushButton_CreateConfig_clicked()
{
    if (ui->lineEdit_InventoryName->text().isEmpty() || ui->lineEdit_LanguageCode->text().isEmpty()){
        QMessageBox::warning(this, (QString::fromUtf8("Error")),
                             QString::fromUtf8("<h2>Missing information</h2>"
                                               "<p>Please fill in an inventory name and the language code.</p>"));
    } else {

        writeSettings();
        QFile in(exe.absolutePath()+"/.data/boss/boss3conf.example");  //Examplefile
        QFile out(dir.absolutePath()+"/boss3conf.xml");   //Destinationfile
        QString line;
        if ( in.open(QIODevice::ReadOnly)&&out.open(QIODevice::WriteOnly)) {
            // files opened successfully
            logDate();
            QTextStream instream( &in );        // use a text stream
            QTextStream outstream( &out );        // use a text stream

            // until end of file...
            while ( !instream.atEnd()) {
                // read and parse a line
                line = instream.readLine();
                // do something with the line
                line.replace(QRegExp("Inventoryname"),ui->lineEdit_InventoryName->text());
                line.replace(QRegExp("/Languagecode/"), "/"+ui->lineEdit_LanguageCode->text()+"/");
                line.replace(QRegExp("\"Languagecode\""), "\""+ui->lineEdit_LanguageCode->text()+"\"");
                line.replace(QRegExp("boss_Languagecode"), "boss_"+ui->lineEdit_LanguageCode->text());
                // std::cout << line.toUtf8().data() << std::endl;
                // write the output
                outstream << line.toUtf8().data() << "\n";
            }

            // Close the files
            in.close();
            out.close();

            writeToLog("echo \"boss3conf.xml created\" >> "+dir.absolutePath()+"/"+korpusname+".log");
            scriptDone();
            check_existing_files();
        }
    }
}


void BofuGui::on_pushButton_EditConfig_clicked()
{
    openURL(QUrl( ""+dir.absolutePath()+"/boss3conf.xml"));
}

/********************************************************************************************/

//5.10.2
void BofuGui::on_pushButton_CreateSQL_clicked()
{
    if (ui->lineEdit_InventoryName->text().isEmpty() || ui->lineEdit_LanguageCode->text().isEmpty()){
        QMessageBox::warning(this, (QString::fromUtf8("Error")),
                             QString::fromUtf8("<h2>Missing information</h2>"
                                               "<p>Please fill in an inventory name and the language code.</p>"));
    } else {
        logDate();
        writeSettings();
        QString line;
        //Example-files
        QString* inFiles[6] = {new QString(exe.absolutePath()+"/.data/sql/create_inv_tables.example"), new QString(exe.absolutePath()+"/.data/sql/create_phon_table.example"),
                               new QString(exe.absolutePath()+"/.data/sql/create_trans_tables.example"), new QString(exe.absolutePath()+"/.data/sql/delete_inv_tables.example"),
                               new QString(exe.absolutePath()+"/.data/sql/delete_phon_table.example"), new QString(exe.absolutePath()+"/.data/sql/delete_trans_tables.example")};
        //Destination-files
        QString* outFiles[6] = {new QString(dir.absolutePath()+"/sql/create_inv_tables.sql"), new QString(dir.absolutePath()+"/sql/create_phon_table.sql"),
                                new QString(dir.absolutePath()+"/sql/create_trans_tables.sql"), new QString(dir.absolutePath()+"/sql/delete_inv_tables.sql"),
                                new QString(dir.absolutePath()+"/sql/delete_phon_table.sql"), new QString(dir.absolutePath()+"/sql/delete_trans_tables.sql")};
        //Text for log
        QString* logText[6] = {new QString("create_inv_tables.sql"), new QString("create_phon_table.sql"), new QString("create_trans_tables.sql"),
                               new QString("delete_inv_tables.sql"), new QString("delete_phon_table.sql"), new QString("delete_trans_tables.sql")};
        for (int i=0; i< 6; i++){
            QFile in(inFiles[i]->toUtf8());  //Examplefile
            QFile out(outFiles[i]->toUtf8());   //Destinationfile

            if ( in.open(QIODevice::ReadOnly)&&out.open(QIODevice::WriteOnly)) {
                // files opened successfully
                QTextStream instream( &in );        // use a text stream
                QTextStream outstream( &out );        // use a text stream

                // until end of file...
                while ( !instream.atEnd()) {
                    // read and parse a line
                    line = instream.readLine();
                    // do something with the line
                    line.replace(QRegExp("Inventoryname"),ui->lineEdit_InventoryName->text());
                    line.replace(QRegExp("_Languagecode"), "_"+ui->lineEdit_LanguageCode->text());
                    // std::cout << line.toUtf8().data() << std::endl;
                    // write the output
                    outstream << line.toUtf8().data() << "\n";
                }

                // Close the files
                in.close();
                out.close();
                writeToLog("echo \""+logText[i]->toUtf8()+" created\" >> "+dir.absolutePath()+"/"+korpusname+".log");
            }
        }
        scriptDone();
    }
}

void BofuGui::on_pushButton_OpenSQLFolder_clicked()
{
    openURL(QUrl( ""+dir.absolutePath()+"/sql/"));
}



/********************************************************************************************/
